package com.zhanglijie.improve.aqs.mix.readwrite.sysdemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/10/23 0023 19:49
 */
public class ReadWriteTestDemo {
    public static void main(String[] args) {
        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        Lock readLock = reentrantReadWriteLock.readLock();
        Lock writeLock = reentrantReadWriteLock.writeLock();

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                readLock.lock();
                try{
                    System.out.println(Thread.currentThread().getName()+"获得到读锁");
                    Thread.sleep(1000);
                }catch (Exception e){

                } finally {
                    System.out.println(Thread.currentThread().getName()+"释放读锁");
                    readLock.unlock();
                }
            },"read_"+i).start();
        }

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                writeLock.lock();
                try{
                    System.out.println(Thread.currentThread().getName()+"获得到写锁");
                    Thread.sleep(1000);
            }catch (Exception e){

            }finally {
                    System.out.println(Thread.currentThread().getName()+"释放写锁");
                    writeLock.unlock();
                }
            },"write_"+i).start();
        }

    }

}
